#ifndef __M_THREAD_H__
#define __M_THREAD_H__

#include "noncopy.h"

#include <thread>
#include <atomic>

// https://github.com/caozhiyi/foundation/blob/master/foundation/thread/thread.h
class Thread : public NonCopyable {
private:
	typedef std::unique_ptr<std::thread> thr_sp;

private:
	std::atomic_bool start_;
	thr_sp thread_;

public:
	Thread(): start_(false) { }
	bool is_start() const { return start_; }
	virtual void stop() { start_ = false; }

	void start() {
		start_ = true;
		if (!thread_) {
			thread_ = thr_sp(new std::thread(std::bind(&Thread::run, this)));
		}
	}

	void join() {
		if (thread_ && thread_->joinable()) {
			thread_->join();
		}
	}

public:
	static void run_in_thread(const Runnable& r) {
		std::thread thr([r]() { r(); });
		thr.detach();
	}

public:
	virtual void run() = 0;
};

#endif // __M_THREAD_H__